package com.ruoyi.project.erp.sossend.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.github.pagehelper.PageInfo;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.project.erp.so.domain.So;
import com.ruoyi.project.erp.so.service.ISoService;
import com.ruoyi.project.erp.sos.domain.Sos;
import com.ruoyi.project.erp.sos.service.ISosService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.erp.sossend.domain.Sossend;
import com.ruoyi.project.erp.sossend.service.ISossendService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;

import javax.annotation.Resource;

/**
 * 订单发货明细Controller
 * 
 * @author ruoyi
 * @date 2020-10-20
 */
@Controller
@RequestMapping("/erp/sossend")
public class SossendController extends BaseController
{
    private String prefix = "erp/sossend";

    @Autowired
    private ISossendService sossendService;
    @Resource
    private ISosService sosService;
    @Resource
    private ISoService soService;

    @RequiresPermissions("erp:sossend:view")
    @GetMapping()
    public String sossend()
    {
        return prefix + "/sossend";
    }

    /**
     * 查询订单发货明细列表
     */
    @RequiresPermissions("erp:sossend:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(long mid)
    {
        //startPage();
        Integer pageNum = ServletUtils.getParameterToInt(Constants.PAGE_NUM);
        Integer pageSize =ServletUtils.getParameterToInt(Constants.PAGE_SIZE);
        Sossend sossend = new Sossend();
        sossend.setIds(mid);
        List<Sossend> list = sossendService.selectSossendList(sossend);
        List<Sossend> resultList = new ArrayList<>();
        int totalPage = list.size()/pageSize+1;
        int count = pageNum*pageSize;
        if (pageNum == totalPage){
            count = list.size();
        }
        for(int start = (pageNum-1)*pageSize;start<count;start++){
            resultList.add(list.get(start));
        }
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(0);
        rspData.setRows(resultList);
        rspData.setTotal(new PageInfo(list).getTotal());
        return getDataTable(list);
    }

    /**
     * 导出订单发货明细列表
     */
    @RequiresPermissions("erp:sossend:export")
    @Log(title = "订单发货明细", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Sossend sossend)
    {
        List<Sossend> list = sossendService.selectSossendList(sossend);
        ExcelUtil<Sossend> util = new ExcelUtil<Sossend>(Sossend.class);
        return util.exportExcel(list, "sossend");
    }

    /**
     * 新增订单发货明细
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存订单发货明细
     */
    @Transactional
    @RequiresPermissions("erp:sossend:add")
    @Log(title = "订单发货明细", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(long id,int sendqty,String logcode,String smemo)
    {
        Sos sos = sosService.selectSosById(id);
        Sossend sossend1 = new Sossend();
        sossend1.setIds(sos.getId());
        List<Sossend> sossendList = sossendService.selectSossendList(sossend1);
        int sum =0;
        for(Sossend temp :sossendList){
                sum += temp.getSendqty();
        }
        if((sum+sendqty) >sos.getQty()){
            return error("发货数量超过订货数量，添加失败");
        }else{
            //活动订单详细表内容
            /*Sos sos = sosService.selectSosById(id);*/
            Sossend sossend = new Sossend();
            sossend.setIds(sos.getId());
            sossend.setLogcode(logcode);
            sossend.setPcode(sos.getPcode());
            sossend.setItemcode(sos.getItemcode());
            sossend.setPname(sos.getPname());
            sossend.setPstd(sos.getPstd());
            sossend.setSendqty(sendqty);
            sossend.setSmemo(smemo);
            int num = sossendService.insertSossend(sossend);
            if(num>0){
                //判断是否发货完毕,修改发货数量
                Sos sos1 = new Sos();
                sos1.setId(id);
                if(sos.getQty() == (sos.getSendqty()+sendqty)){
                    sos1.setSts("发货完成");
                    sos1.setSendqty(sos.getSendqty()+sendqty);
                }else{
                    sos1.setSts("发货中");
                    sos1.setSendqty(sos.getSendqty()+sendqty);
                }
                sosService.updateSos(sos1);
                //判断主表是否发货完毕
                So so = soService.selectSoById(sos.getMid().toString());
                //查询所有子表是否发货完毕
                Sos sos2 =new Sos();
                sos2.setMid(sos.getMid());
                List<Sos> sosList = sosService.selectSosList(sos2);
                int i=0;
                So so1 = new So();
                so1.setId(so.getId());
                for(Sos temp :sosList){
                    if(!"发货完成".equals(temp.getSts())){
                        so1.setSt("发货中");
                        break;
                    }
                    i++;
                }
                if(i>=sosList.size()){
                    so1.setSt("发货完成");
                }
                soService.updateSo(so1);
            }
            return new AjaxResult(AjaxResult.Type.SUCCESS,"添加成功",num);
        }
    }

    /**
     * 修改订单发货明细
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        Sossend sossend = sossendService.selectSossendById(id);
        mmap.put("sossend", sossend);
        return prefix + "/edit";
    }
/*
    *//**
     * 批量发货
     *//*
    @GetMapping("/listSosSend/{id}")
    public String listSosSend(@PathVariable("id") Long id, ModelMap mmap)
    {  //新增发货信息
        mmap.put("mid", id);
        return prefix + "/sossend";
    }*/

    /**
     * 修改保存订单发货明细
     */
    @RequiresPermissions("erp:sossend:edit")
    @Log(title = "订单发货明细", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Sossend sossend)
    {
        Sos sos = sosService.selectSosById(sossend.getIdsos());
        Sossend sossend1 = new Sossend();
        sossend1.setIdsos(sos.getId());
        List<Sossend> sossendList = sossendService.selectSossendList(sossend1);
        int sum =0;
        for(Sossend temp :sossendList){
            if(!temp.getId().equals(sossend.getId())){
                sum += temp.getSendqty();
            }
        }
        if((sum+sossend.getSendqty()) >sos.getQty()){
            return error("发货数量超过订货数量，修改失败");
        }else{
            int num = sossendService.updateSossend(sossend);
            Sos sos1 =  new Sos();
            sos1.setId(sossend.getIdsos());
            if((sum+sossend.getSendqty()) == sos.getQty()){
                //判断已完成
                sos1.setSts("发货完成");
                sos1.setSendqty(sum+sossend.getSendqty());
            }else{
                sos1.setSts("发货中");
                sos1.setSendqty(sum+sossend.getSendqty());
            }
            sosService.updateSos(sos1);
            //判断主表是否完成
            So so = soService.selectSoById(sos.getMid().toString());
            //查询所有子表是否发货完毕
            Sos sos2 =new Sos();
            sos2.setMid(sos.getMid());
            List<Sos> sosList = sosService.selectSosList(sos2);
            int i=0;
            So so1 = new So();
            so1.setId(so.getId());
            for(Sos temp :sosList){
                if(!"发货完成".equals(temp.getSts())){
                    so1.setSt("发货中");
                    break;
                }
                i++;
            }
            if(i>=sosList.size()){
                so1.setSt("发货完成");
            }
            soService.updateSo(so1);
            return toAjax(num);
        }
    }

    /**
     * 删除订单发货明细
     */
    @RequiresPermissions("erp:sossend:remove")
    @Log(title = "订单发货明细", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        //修改订单发货数量
        Sossend sossend =sossendService.selectSossendById(Long.parseLong(ids));
        int num = sossendService.deleteSossendByIds(ids);
        Sos sos = sosService.selectSosById(sossend.getIdsos());
        Sos temp = new Sos();
        temp.setId(sos.getId());
        temp.setSendqty(sos.getSendqty()-sossend.getSendqty());
        temp.setSts("发货中");
        sosService.updateSos(temp);
        //修改订单主表状态
        So so = soService.selectSoById(sos.getMid().toString());
        So tempSo = new So();
        tempSo.setId(so.getId());
        tempSo.setSt("发货中");
        soService.updateSo(tempSo);
        return toAjax(num);
    }

    /**
     * 查看发货记录
     */
    @GetMapping("/view/{mid}")
    public String view(@PathVariable("mid") Long mid, ModelMap mmap)
    {
        mmap.put("mid", mid);
        return prefix + "/sossend";
    }

    /**
     * 确认收货
     */
    @Log(title = "确认收货", businessType = BusinessType.DELETE)
    @PostMapping( "/sureReceive")
    @ResponseBody
    public AjaxResult sureReceive(String sendCode,String id,String sossendId,String recemp,String smemo)
    {
        Sossend sossend = new Sossend();
        sossend.setSendcode(sendCode);
        sossend.setIds(Long.parseLong(id));
        sossend.setRecemp(recemp);
        sossend.setRecdt(new Date());
        sossend.setSmemo(smemo);
        sossend.setSt("收货");
        int num = sossendService.updateSossendBatch(sossend);
        if(num >0){
            //修改订单主表状态
            int sum=0;
            Sossend sossend1 = sossendService.selectSossendById(Long.parseLong(sossendId));
            //获取订单详情
            Sos sos = sosService.selectSosById(sossend1.getIdsos());

            Sossend temp = new Sossend();
            temp.setIdsos(sossend1.getIdsos());
            List<Sossend> sossendList = sossendService.selectSossendList(temp);
            int i;
            for(i=0;i<sossendList.size();i++){
                Sossend sossend2 = sossendList.get(i);
                sum += sossend2.getSendqty();
                if("发货".equals(sossend2.getSt())){
                    break;
                }
            }
            Sos sos1 = new Sos();
            sos1.setId(sossend1.getIdsos());
            if(sum == sos.getSendqty() && i>=sossendList.size()){
                sos1.setSts("收货完成");
            }else if(sum == sos.getSendqty()){
                sos1.setSts("发货完成");
            }else{
                sos1.setSts("发货中");
            }
            //修改订单主表状态
            So so = soService.selectSoById(sossend1.getIds().toString());
            Sos sos2 = new Sos();
            sos2.setMid(Long.parseLong(so.getId()));
            List<Sos> sosList = sosService.selectSosList(sos2);
            int j;
            for(j=0;j<sosList.size();j++){
                if(!"收货完成".equals(sosList.get(j))){
                    break;
                }
            }
            So so1 = new So();
            so1.setId(sossend1.getIds().toString());
            if(j>=sosList.size()){
                so1.setSt("收货完成");
                soService.updateSo(so1);
            }
        }
        return toAjax(num);
    }

    /**
     * 新增订单发货明细
     */
    @GetMapping("/sossendnew")
    public String sossendnew()
    {
        return prefix + "/sossendnew";
    }

    /**
     * 查询订单发货明细列表
     */
    @RequiresPermissions("erp:sossend:list")
    @PostMapping("/listNew")
    @ResponseBody
    public TableDataInfo listNew(Sossend sossend)
    {
        //startPage();
        Integer pageNum = ServletUtils.getParameterToInt(Constants.PAGE_NUM);
        Integer pageSize =ServletUtils.getParameterToInt(Constants.PAGE_SIZE);
        List<Sossend> list = sossendService.selectSossendList(sossend);
        List<Sossend> resultList = new ArrayList<>();
        int totalPage = list.size()/pageSize+1;
        int count = pageNum*pageSize;
        if (pageNum == totalPage){
            count = list.size();
        }
        for(int start = (pageNum-1)*pageSize;start<count;start++){
            resultList.add(list.get(start));
        }
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(0);
        rspData.setRows(resultList);
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }
}
